from baseview import BaseView
from ..devicetree import DeviceTree
from ..bases import widgets
from .. import editors

class DefinitionsView(BaseView):
    topwidget_name = 'Device Definitions'
    topwidget_cls = widgets.HPane
    def __init__(self, **kwargs):
        self.topwidget = widgets.VBox()
        super(DefinitionsView, self).__init__(**kwargs)
        self.DeviceSystem = self.MainController.DeviceSystem

        self.device_editor = None
        
        frame = self.make_child_widget(widgets.Frame, 'frame1', label='Devices')
        col_names = ['id', 'name']
        obj_names = ['DefinedDevice']
        self.device_list = DeviceTree(col_names=col_names, obj_names=obj_names, child_name_attr='none', 
                                      show_dicts=False, base_dict=self.DeviceSystem.DefinedDevices, used_columns=[1])
        self.device_list.widget.connect('selection_changed', self.on_device_list_selection_changed)
        frame.pack_start(self.device_list.widget.topwidget, expand=True)
        
        hbox = widgets.HBox()
        d = {'btnNewDevice':'New Device', 'btnDelDevice':'Delete'}
        for k, v in d.iteritems():
            btn = self.make_child_widget(widgets.Button, k, label=v)
            btn.connect('clicked', self.on_device_list_btns_clicked, k)
            hbox.pack_start(btn)
        frame.pack_start(hbox)
        
        self.topcontainer.pack_start(frame)
        
        self.DeviceSystem.connect('new_device', self.on_ds_new_device)
        
        self.topwidget.show_all()
        
    def set_current_device(self, obj):
        if self.device_editor is not None:
            self.remove_editor(self.device_editor)
        self.add_editor(editors.DeviceEditor, 'device_editor', device=obj)
        self.topcontainer.pack_start(self.device_editor.topwidget)
        
    def on_device_list_selection_changed(self, **kwargs):
        obj = kwargs.get('obj')
        state = kwargs.get('state')
        if state and hasattr(obj, 'id'):
            self.set_current_device(obj)
        
    def on_device_list_btns_clicked(self, btn, key):
        if key == 'btnNewDevice':
            device = self.DeviceSystem.add_definition(name='New Device')
            self.device_list.tree.set_selection(device.id)
        elif key == 'btnDelDevice':
            obj = self.device_list.widget.selected_obj
            if obj is not None:
                self.DeviceSystem.del_definition(device=obj)
                self.device_list.tree.refresh_all()
        
    def on_ds_new_device(self, **kwargs):
        self.device_list.tree.refresh_all()
        
